package com.zx.sa.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import reactor.core.publisher.Flux;

@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/advisors")
public class ChatAdvisorsController {

    private final ChatClient chatClient;

    @Autowired
    public ChatAdvisorsController(ChatModel chatModel, ChatMemory chatMemory2) {
        // 自定义上下文存储(使用内存存储，整个项目共用一个会话)
        ChatMemoryRepository repository = new InMemoryChatMemoryRepository();
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(repository)
                .maxMessages(5)
                .build();

        this.chatClient= ChatClient.builder(chatModel)
                // 设置默认的角色
                .defaultSystem("你是张雪的个人生活管家，回答各种问题！")
                // 在使用 Chat Memory 时，可以实现 Spring AI 存储上下文。
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                // 实现 Logger 的 Advisor
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
    }

    @RequestMapping("/index")
    public String index() {
        return "advisors";
    }


    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public Flux<String> chat(@RequestParam(value = "msg", defaultValue = "") String msg) {
        return chatClient.prompt().user(msg).stream().content();
    }

} 